import Row from '../../../_antd1.11.2/Row';
import Col from '../../../_antd1.11.2/Col';
import Modal from '../../../_antd1.11.2/Modal';
import Button from '../../../_antd1.11.2/Button';
import Icon from '../../../_antd1.11.2/Icon';
import message from '../../../_antd1.11.2/message'
import Table from '../../../_antd1.11.2/table';
import Dropdown from '../../../_antd1.11.2/dropdown';
import Menu from '../../../_antd1.11.2/menu';
import Form from '../../../_antd1.11.2/form';
const MenuItem = Menu.Item;
const FormItem = Form.Item;

import WeaTools from '../../wea-tools';
import WeaScroll from '../../wea-scroll';
import WeaSelect from '../../wea-select';
import WeaBrowser from '../../wea-browser';
import WeaScope from '../../wea-scope';
import WeaSelectGroup from '../../wea-select-group';
import WeaAssociativeSearchMult from '../wea-associative-search-mult';

import isEqual from 'lodash/isEqual';

//国际化 zxt- 20170419
const defaultLocale = {
  	total: '共',
  	totalUnit: '条',
  	operates: '操作',
  	delete: '删除',
  	customColSave: '保存',
  	customColCancel: '取消',
};


class Main extends React.Component {
	//国际化 zxt- 20170419
	static contextTypes = {
	    antLocale: React.PropTypes.object,
	}
	getLocale() {
	    let locale = {};
	    if (this.context.antLocale && this.context.antLocale.Table) {
	    	locale = this.context.antLocale.WeaTable;
	    }
	    return { ...defaultLocale, ...locale, ...this.props.locale };
  	}
    constructor(props) {
        super(props);
        this.state = {
        	conditions: [],
        	labels: {},
        	//table
        	columns: [],
        	datas: this.addKeytoDatas(props.replaceDatas) || [],
        	selectedRowKeys: [],
        	pageSize: 10,
        	//select
        	selectDatas: {},
        	//modal
        	visible: false,
        	_visible: false,
        	addDatas: [],
        	addDatasInit: [],
        }
        this.onBrowerChange = this.onBrowerChange.bind(this);
        this.onBrowerClick = this.onBrowerClick.bind(this);
        this.onOk = this.onOk.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.onClear = this.onClear.bind(this);
        this._onOk = this._onOk.bind(this);
        this._onCancel = this._onCancel.bind(this);
		this.doAdd = this.doAdd.bind(this);
    }
    componentDidMount() {
//  	const datas_mock = [
//		      	{
//		      		sharetype: 1,
//		      		sharetypespan: "人员",
//			        relatedshare: "6084",
//			        relatedsharespan: "韩佳人6",
//			        relatedshareurl: '/',
//		      	},
//			    {
//			    	sharetype: 6,
//			    	sharetypespan: "岗位",
//			        relatedshare: "88",
//			        relatedsharespan: "20140202",
//			        relatedshareurl: "/",
//			        joblevel: "2",
//			        joblevelspan: "总部",
//			        joblevelurl: "/",
//			        jobfield:'5',
//			        jobfieldspan:'下级分部',
//			        jobfieldurl: '/',
//			    },
//	    ];
	    const { replaceDatas = [] } = this.props;
    	this.getDates();
      	this.setState({ datas: replaceDatas, selectDatas: this.getSelectDatas(this.addKeytoDatas(replaceDatas)) });
//  	this.setState({
//  		datas: this.addKeytoDatas(datas_mock),
//  		selectDatas: this.getSelectDatas(this.addKeytoDatas(datas_mock))
//  	});
    }
    componentWillReceiveProps(nextProps){
	    const { replaceDatas = [] } = this.props;
    	const nextReplaceDatas = nextProps.replaceDatas || [];
    	if(!isEqual(replaceDatas,nextReplaceDatas)){
    		this.setState({ 
    			datas: this.addKeytoDatas(nextReplaceDatas),
    			selectDatas: this.getSelectDatas(this.addKeytoDatas(nextReplaceDatas)) 
    		});
    	}
    }
    render() {
    	const { inputStyle = {}, type = '141', modalStyle = {} } = this.props;
    	const { datas, selectDatas, visible, _visible, selectedRowKeys } = this.state;
        const buttons = [
            <Button key="submit" type="primary" size="large" onClick={this.onOk} disabled={false}>确 定</Button>,
            <Button key="clear" type="ghost" size="large" onClick={this.onClear}>清 除</Button>,
            <Button key="back" type="ghost" size="large" onClick={this.onCancel}>取 消</Button>
       	];
       	const _buttons = [
            <Button key="submit" type="primary" size="large" onClick={this._onOk} >保 存</Button>,
            <Button key="back" type="ghost" size="large" onClick={this._onCancel}>取 消</Button>
       	];
        return (
          	<div className='wea-hrm-condition'>
            	<WeaAssociativeSearchMult
	                {...this.props}
	                style={ inputStyle }
	                datas={ selectDatas }
	                selectedValues={this.getSelectKeys()}
	                isClearData={JSON.stringify(selectDatas) === '{}'}
	                type={type}
	                clickCallback={this.onBrowerClick}
	                onChange={this.onBrowerChange}
	            />
            	<Modal wrapClassName="wea-hr-muti-input"
		            title={this.getTitle()}
		            width={modalStyle.width}
		            maskClosable={false}
		            visible={visible}
		            onCancel={this.onCancel}
		            footer={buttons}
		        >
		            <div className='wea-table-edit wea-hrm-condition-table' style={{height: 460}}>
		            	<Row className="wea-table-edit-title" >
							<Col>
								{ '已添加条件' }
								<Button type="primary" disabled={!`${selectedRowKeys}`} title='删除' size="small" onClick={this.doDelete.bind(this,selectedRowKeys)} ><Icon type="minus" /></Button>
								<Button type="primary"  title='新增' size="small" onClick={this.doAdd}><Icon type="plus" /></Button>
							</Col>
			            </Row>
                        <WeaScroll className="wea-scroll" typeClass="scrollbar-macosx" style={{height: 410}}>
                            <Table 
			                	columns={this.getColumns()}
			                	dataSource={datas}
			                	pagination={this.getPagination()}
			                	rowSelection={this.getRowSelection()}
			                />
                        </WeaScroll>
		            </div>
		            <Modal wrapClassName="wea-hr-muti-input" 
			            title={this.getTitle(true)}
			            width={modalStyle.width * 0.6}
			            maskClosable={false}
			            visible={_visible}
			            onCancel={this._onCancel}
			            footer={_buttons}
			        >
			            {this.getAddComponent()}
		            </Modal>
	            </Modal>
          	</div>
        );
    }
    //添加条件
    doAddComponentChange(type, key, value, list, url){
    	const { addDatas, conditions } = this.state;
    	let _addDatas = [].concat(addDatas);
    	if(value){
	    	if(type === 'BROWSER') {
	    		const isLev = key === 'jobfield';
	    		let ids = value.split(',');
	    		_addDatas = [];
    			if(isLev){
		    		addDatas.map(addData => {
	    				let _addData = {...addData};
    					_addData[key] = value;
    					let spans = [];
    					ids.map((id,i) => {
    						spans.push(list[i]['name'] || list[i]['lastname'])
    					});
    					_addData[key + 'span'] = spans.join(',');
    					_addData[key + 'url'] = url;
    					_addDatas.push(_addData);
		    		})
    			}else{
    				ids.map((id,i) => {
    					let _addData = {...addDatas[0]};
    					_addData[key] = id;
    					_addData[key + 'span'] = list[i]['name'] || list[i]['lastname'];
    					_addData[key + 'url'] = `${url}${id}`;
    					_addDatas.push(_addData);
    				});
    			}
	    	}
		    if(type === 'SELECT') {
		    	const init = key === 'sharetype';
	    		_addDatas = _addDatas.map(addData => {
	    			let _addData = init ? {} : {...addData};
	    			let hasSec = false;
	    			init && conditions[1][value].map(condition => {
	    				if(condition.conditionType === 'INPUT_INTERVAL' && condition.domkey[0] === 'seclevel')
	    					hasSec = true;
	    				if(condition.conditionType === 'SELECT' || condition.conditionType === 'SELECT_LINKAGE')
		    				condition.options.map(o => {
		    					if(o.selected === true){
		    						_addData[condition.domkey[0]] = o.key;
		    						_addData[condition.domkey[0] + 'span'] = o.showname;
		    					}
		    				});
	    			});
	    			if(hasSec) _addData.seclevel = '0-100';
	    			list.map(l => {
	    				if(l.key === value){
	    					_addData[key] = value;
	    					_addData[key + 'span'] = l.showname;
	    					if(url)	_addData[key + 'url'] = `${url}${value}`;
	    				}
	    			})
	    			return _addData
	    		})
		    }
		    if(type === 'INPUT_INTERVAL'){
		    	_addDatas = _addDatas.map(addData => {
		    		let _addData = {...addData};
					_addData[key] = `${value}-${list}`;
					//_addData[key + 'span'] = url;
		    		return _addData
		    	})
		    }
	    }
	    this.setState({addDatas:_addDatas})
    }
    getAddComponent(){
    	const { conditions, addDatas } = this.state;
    	if(!`${conditions}`) return null;
    	const index = addDatas[0].sharetype;
    	return (
    		<div style={{ padding: 20 }}>
    			<FormItem
                    label={conditions[0].label}
                    labelCol={{span: conditions[0].labelcol}}
                    wrapperCol={{span: conditions[0].fieldcol}}>
                        <WeaSelect
                        	value={index}
    						onChange={v => this.doAddComponentChange('SELECT',conditions[0].domkey[0],v,conditions[0].options)}
		                    options= {conditions[0].options}
		                />
                </FormItem>
				{
					conditions[1][index].map(condition => {
						let showDropMenu = false;
						let replaceDatas = [];
						let startValue = 0;
						let endValue = 100;
						if(condition.conditionType === 'BROWSER') {
							if(condition.browserConditionParam)
								showDropMenu = condition.browserConditionParam.type=='4' || condition.browserConditionParam.type=='164';//部门分部显示维度菜单
							addDatas.map(addData => {
								addData[condition.domkey[0]] && replaceDatas.push({
									id:addData[condition.domkey[0]] || '',
									name: addData[`${condition.domkey[0]}span`] || '',
								})
							});
						}
						if(condition.conditionType === 'INPUT_INTERVAL' && addDatas[0][condition.domkey[0]]){
							const value = addDatas[0][condition.domkey[0]].split('-');
							startValue = Number(value[0]);
							endValue = Number(value[1]);
						}
						return (
							<FormItem
			                    label={condition.label}
			                    labelCol={{span: condition.labelcol}}
			                    wrapperCol={{span: condition.fieldcol}}>
			    					{
			    						condition.conditionType === 'SELECT' && 
				    					<WeaSelect
				    						value={addDatas[0][condition.domkey[0]] || '1'}
				    						onChange={v => this.doAddComponentChange('SELECT',condition.domkey[0],v,condition.options)}
						                    options= {condition.options}
						                />
			    					}
			    					{
			    						condition.conditionType === 'BROWSER' && 
			    						<WeaBrowser {...condition.browserConditionParam}
			    							replaceDatas={replaceDatas}
			    							showDropMenu={showDropMenu}
			    							onChange={(v, name, list) => this.doAddComponentChange('BROWSER',condition.domkey[0],v,list,condition.browserConditionParam.linkUrl)}
			    						/>
			    						
			    					}
			    					{
			    						condition.conditionType === 'INPUT_INTERVAL' && 
			    						<WeaScope 
			    							min={[0,100]}
			    							max={[0,100]}
			    							domkey={condition.domkey}
			    							startValue={startValue}
			    							endValue={endValue}
			    							onChange={(start, end) => this.doAddComponentChange('INPUT_INTERVAL',condition.domkey[0],start,end)}
			    						/>
			    					}
			    					{
			    						condition.conditionType === 'SELECT_LINKAGE' && 
			    						<WeaSelectGroup 
			    							domkey={condition.domkey}
			    							options={condition.options}
			    							selectLinkageDatas={condition.selectLinkageDatas}
			    							onChange={(v, b) => {
			    								this.doAddComponentChange('SELECT',condition.domkey[0],v,condition.options);
			    								b && b.length && b.length > 0 && this.doAddComponentChange('BROWSER',condition.domkey[1],b[0],b[2],condition.selectLinkageDatas[v].browserConditionParam.linkUrl)
			    							}}
			    						/>
			    					}
			                </FormItem>
						)
					})
				}
			</div>
    	)
    }
    //util
    getDates(){
		let { conditionURL = '' } = this.props;
    	WeaTools.callApi(conditionURL).then(datas => {
    		const { conditions, columns, labels } = datas;
    		const addDatas = [{ sharetype: conditions[0].options[0].key, sharetypespan: conditions[0].options[0].showname }];
    		this.setState({ conditions, columns, labels, addDatas, addDatasInit: addDatas });
    	})
    }
    addKeytoDatas(datas){
		let _datas = datas.map((data, i) => {
			let _data = {...data};
			_data.key = i
			return _data
		})
		return _datas
	}
    getSelectDatas(datas){
    	let { labels } = this.state;
    	let selectDatas = {};
    	datas.map(data => {
    		const { 
    			key,
    			sharetype, sharetypespan,
    			relatedshare, relatedsharespan, relatedshareurl,
    			rolelevel, rolelevelspan, rolelevelurl,
    			joblevel, joblevelspan, joblevelurl,
    			jobfield, jobfieldspan, jobfieldurl,
    			seclevel, seclevelspan,
    		} = data;
    		let name = null;
    		
    		if(relatedshare !== undefined) {
    			name = (
	    			<span>
	    				{sharetypespan}
	    				{'('}
	    				{ relatedshareurl ? <a href={relatedshareurl} target='_blank'>{relatedsharespan}</a> : relatedsharespan}
	    				{')'}
	    			</span>
    			)
    		}
    		
    		if(rolelevel !== undefined) {
    			name = (
	    			<span>
	    				{sharetypespan}
	    				{'('}
	    				{ relatedshareurl ? <a href={relatedshareurl} target='_blank'>{relatedsharespan}</a> : relatedsharespan}
	    				{'/'}
	    				{ rolelevelurl ? <a href={rolelevelurl} target='_blank'>{`${labels.rolelevelprefix || ''}${rolelevelspan}`}</a> : `${labels.rolelevelprefix || ''}${rolelevelspan}`}
	    				{')'}
	    			</span>
    			)
    		}
			if(joblevel !== undefined) {
    			let _jobfield = '';
    			let _jobfieldspan = '';
    			if(jobfield !== undefined){
    				_jobfield = jobfield.split(',');
    				_jobfieldspan = jobfieldspan.split(',');
    			}
    			name = (
	    			<span>
	    				{sharetypespan}
	    				{'('}
	    				{ relatedshareurl ? <a href={relatedshareurl} target='_blank'>{relatedsharespan}</a> : relatedsharespan}
	    				{'/'}
	    				{ rolelevelurl ? <a href={joblevelurl} target='_blank'>{joblevelspan}</a> : joblevelspan}
	    				{ jobfield !== undefined && 
	    					<span>
		    					{'('}
		    					{
		    						_jobfield.map((_jobf, i) => {
		    							if(rolelevelurl){
		    								return <a href={jobfieldurl + _jobf} target='_blank'>{_jobfieldspan[i]}</a>
		    							}
		    							return _jobfieldspan[i]
		    						})
		    					}
		    					{')'}
	    					</span>
	    				}
	    				{')'}
	    			</span>
    			)
			}
    		selectDatas[key] = {
    			id: key,
    			name: (
    				<span>
    					{name}
	    				{seclevel !== undefined && (labels['seclevellabel' + sharetype] ? labels['seclevellabel' + sharetype].replace('{$level$}',seclevel) : seclevel)}
    				</span>
    			)
    		}
    	});
    	return selectDatas;
    }
    //select
    getSelectKeys(){
    	const { selectDatas } = this.state;
    	let selectKeys = [];
    	for(key in selectDatas){
    		selectKeys.push(key);
    	}
    	return selectKeys
    }
    onBrowerClick(){
    	this.setState({visible: true})
    }
    onBrowerChange(values, selectDatas){
    	this.setState({selectDatas})
    }
    //table
    getColumns(){
    	const { columns, conditions } = this.state;
		let _columns = [].concat(columns);
		_columns = _columns.map(col => {
			let _col = { ...col };
			if(_col.dataIndex === 'sharetype'){
				_col.render = ( text, record, index ) => {
					return record.sharetypespan
				}
			}
			if(_col.dataIndex === 'condition'){
				_col.render = ( text, record, index ) => {
					let textArr = [];
					if(record.relatedsharespan !== undefined){
						textArr.push(record.relatedsharespan);
					}
					if(record.joblevelspan !== undefined){
						textArr.push(record.joblevelspan);
					}
					if(record.rolelevelspan !== undefined){
						textArr.push(record.rolelevelspan);
					}
					let newText = textArr.join(' /');
					if(record.jobfieldspan !== undefined){
						newText += `(${record.jobfieldspan})`;
					}
					return newText
				}
			}
			return _col
		});
		const locale = this.getLocale();
		_columns.push({
			title: '',
			dataIndex: 'ops',
			key: 'ops',
			width: 80,
            className:"wea-table-operates",
            render: ( text, record, index )=> {
            	const menu = (
            		<Menu>
                        <MenuItem>
	                        <a href='javascript:void(0);' onClick={this.doDelete.bind(this,[record.key])}>{locale.delete}</a>
	                    </MenuItem>
                    </Menu>
            	)
            	return (
                    <div className='wea-hrm-condition-table-ops'>
                        <Dropdown overlay={menu}>
                            <span>
                                {locale.operates} <Icon type="caret-down" />
                            </span>
                        </Dropdown>
                    </div>
                )
            }
		});
		return _columns
    }
    getPagination() {
		return false
	}
    getRowSelection(){
		const { columns, selectedRowKeys } = this.state;
		if(!`${columns}`) return null
		const rowSelection = {
			selectedRowKeys,
			onChange: (sRowKeys, selectedRows) => {
				this.setState({selectedRowKeys : sRowKeys});
			}
		}
		return rowSelection
	}
    //btns
    doAdd(){
    	this.setState({_visible: true})
    }
    doDelete(keys){
    	const { datas } = this.state;
    	let _datas = [].concat(datas);
    	keys.map(key => {
    		_datas = _datas.filter(_data => _data.key !== key)
    	});
    	_datas = this.addKeytoDatas(_datas);
    	this.setState({
    		datas: _datas,
    		selectedRowKeys: [],
    		selectDatas: this.getSelectDatas(_datas),
    	});
    }
    //modal
    getTitle(bool){
    	const { icon = '', title = '人力资源条件', iconBgcolor = ''} = this.props;
    	return (
    		<Row>
                <Col span="8" style={{ paddingLeft:20, lineHeight:'48px' }}>
                    <div className="wea-hr-muti-input-title">
                        {iconBgcolor ? <div className="wea-workflow-radio-icon-circle" style={{background:iconBgcolor ? iconBgcolor : ""}}><i className={icon}/></div>
                        : <span style={{verticalAlign:'middle',marginRight:10}}><i className={icon}/></span>}
                        <span style={{verticalAlign:'middle'}}>{ bool ? '添加条件' : title}</span>
                    </div>
                </Col>
            </Row>
    	)
    }
    onOk(){
    	const { datas } = this.state;
    	this.setState({visible: false});
    	if(typeof this.props.onChange === 'function'){
	    	let _datas = datas.map((data, i) => {
				let _data = {...data}
				delete _data.key
				return _data
			});
	    	this.props.onChange('', '', _datas);
    	}
    }
    onClear(){
    	this.setState({
    		selectDatas: {},
    		datas: [],
    		selectedRowKeys: []
    	})
    }
    onCancel(){
    	const { replaceDatas = [] } = this.props;
    	this.setState({
    		datas: this.addKeytoDatas(replaceDatas),
    		selectDatas: this.getSelectDatas(this.addKeytoDatas(replaceDatas)),
    		selectedRowKeys: [],
    		visible: false,
    	})
    }
    _onOk(){
    	const { datas, addDatas, addDatasInit } = this.state;
    	let _datas = [].concat(datas);
    	let _addDatas = [].concat(addDatas);
    	_addDatas = _addDatas.map((addData, i)=> {
    		let _addData = {...addData};
    		_addData.key = datas.length + i;
    		return _addData
    	})
    	if(_addDatas.length > 0){
    		_datas = _datas.concat(_addDatas)
    		this.setState({
    			_visible: false, 
    			datas: _datas, 
    			selectDatas: this.getSelectDatas(_datas),
    			addDatas: addDatasInit,
    		})
    	}else{
    		message.warning('数据不能为空！',500);
    	}
    }
    _onCancel(){
    	const { addDatasInit } = this.state;
    	this.setState({_visible: false, addDatas: addDatasInit})
    }
}

export default Main;